<template>
  <div class="order-management-view">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入物流单号"
          prefix-icon="el-icon-search"
          size="small"
          style="width: 250px;"
          clearable
          @keyup.enter.native="handleSearch"
        ></el-input>
        <el-select
          v-model="statusFilter"
          placeholder="请选择订单状态"
          size="small"
          style="width: 150px; margin-left: 10px;"
          clearable
        >
          <el-option label="全部状态" :value="''"></el-option>
          <el-option label="待处理" :value="1">
            <el-tag type="warning" size="mini">待处理</el-tag>
          </el-option>
          <el-option label="生产中" :value="2">
            <el-tag type="info" size="mini">生产中</el-tag>
          </el-option>
          <el-option label="已发货" :value="3">
            <el-tag type="primary" size="mini">已发货</el-tag>
          </el-option>
          <el-option label="已签收" :value="4">
            <el-tag type="success" size="mini">已签收</el-tag>
          </el-option>
        </el-select>
        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleSearch">搜索</el-button>
        <el-button size="small" @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 订单列表表格 -->
    <el-table 
      :data="orderList" 
      style="width: 100%; margin-top: 20px;" 
      border 
      v-loading="loading"
    >
      <el-table-column label="序号" width="60px" align="center">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="id" label="订单ID" width="80px" align="center"></el-table-column> -->
       <el-table-column label="企业名称" width="120px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.customer">{{ scope.row.customer.Name }}</span>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
       <el-table-column label="设备信息" width="120px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.devices">{{ scope.row.devices.device_name }}</span>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" width="80px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.device_quantity">{{ scope.row.device_quantity }}</span>
          <span v-else style="color: #999;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="配件信息" width="300px" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.accessory_skus && scope.row.accessory_skus.length > 0" class="accessories-display">
            <div v-for="accessorySku in scope.row.accessory_skus" :key="accessorySku.accessory_id" class="accessory-item">
              <el-tag 
                size="mini"
                class="accessory-name-tag"
                type="primary"
              >
                {{ accessorySku.accessory_name }}{{ accessorySku.sku_value ? ' - ' + accessorySku.sku_value : '' }}
              </el-tag>
            </div>
          </div>
          <div v-else style="color: #999; font-size: 12px;">无配件</div>
        </template>
      </el-table-column>
      <el-table-column label="收货人" width="100px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row && scope.row.recipient_name">{{ scope.row.recipient_name }}</span>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
      <el-table-column label="收货人手机号" width="130px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row && scope.row.recipient_tel">{{ scope.row.recipient_tel }}</span>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" min-width="200px">
        <template slot-scope="scope">
          <span v-if="scope.row && scope.row.recipient_address">{{ scope.row.recipient_address }}</span>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
      <el-table-column label="工厂名称" min-width="200px">
        <template slot-scope="scope">
          <span v-if="scope.row.factory && scope.row.factory.factory_name">{{ scope.row.factory.factory_name }}</span>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
      <el-table-column label="工厂地址" min-width="200px">
        <template slot-scope="scope">
          <span v-if="scope.row.factory && scope.row.factory.address">{{ scope.row.factory.address }}</span>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
      <el-table-column prop="track_number" label="物流单号" width="150px"></el-table-column>
      <el-table-column prop="status" label="订单状态" width="100px" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="物流面单" width="100px" align="center">
        <template slot-scope="scope">
          <el-button 
            v-if="scope.row.logistics_document_img" 
            type="text" 
            size="small" 
            @click="handleViewLogisticsImage(scope.row.logistics_document_img)"
          >
            查看面单
          </el-button>
          <span v-else style="color: #999;">无面单</span>
        </template>
      </el-table-column>
      <el-table-column label="设备图片" width="100px" align="center">
        <template slot-scope="scope">
          <el-button 
            v-if="scope.row.device_img" 
            type="text" 
            size="small" 
            @click="handleViewDeviceImage(scope.row.device_img)"
          >
            查看图片
          </el-button>
          <span v-else style="color: #999;">无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="160px" align="center">
        <template slot-scope="scope">
          {{ formatTime(scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="update_time" label="更新时间" width="160px" align="center">
        <template slot-scope="scope">
          {{ formatTime(scope.row.update_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="120px">
        <template slot-scope="scope">
          <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
      
      <!-- 操作列 -->
      <el-table-column label="操作" width="120px" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleTransferOrder(scope.row)">转单</el-button>
          <el-button type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="handleDeleteOrder(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 修改订单弹窗 -->
    <el-dialog
      title="修改订单"
      :visible.sync="editDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="120px">
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择订单状态" style="width: 100%;">
            <el-option label="待处理" :value="1">
              <el-tag type="warning" size="mini">待处理</el-tag>
            </el-option>
            <el-option label="生产中" :value="2">
              <el-tag type="info" size="mini">生产中</el-tag>
            </el-option>
            <el-option label="已发货" :value="3">
              <el-tag type="primary" size="mini">已发货</el-tag>
            </el-option>
            <el-option label="已签收" :value="4">
              <el-tag type="success" size="mini">已签收</el-tag>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="track_number">
          <el-input v-model="editForm.track_number" placeholder="请输入物流单号"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="editForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="editLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 转单弹窗 -->
    <el-dialog
      title="转单处理"
      :visible.sync="transferOrderDialogVisible"
      width="700px"
      :close-on-click-modal="false"
    >

      <el-form :model="transferForm" :rules="transferRules" ref="transferForm" label-width="100px">
        <el-form-item label="订单信息" prop="orderInfo">
          <div class="order-info-display">
            <!-- <p><strong>订单ID：</strong>{{ transferForm.id }}</p> -->
            <p><strong>设备名称：</strong>{{ transferForm.device_name || '未知' }}</p>
            <p><strong>当前工厂：</strong>{{ transferForm.current_factory || '未知' }}</p>
          </div>
        </el-form-item>
        <el-form-item label="选择工厂" prop="factory_id">
          <el-select 
            v-model="transferForm.factory_id" 
            placeholder="请选择目标工厂" 
            style="width: 100%;"
            filterable
            clearable
          >
            <el-option 
              v-for="factory in factoryList" 
              :key="factory.id" 
              :label="factory.factory_name" 
              :value="factory.id"
            >
              <span>{{ factory.factory_name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ factory.address }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="转单备注" prop="transfer_remark">
          <el-input 
            v-model="transferForm.transfer_remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入转单原因或备注信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="transferOrderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitTransferOrder" :loading="transferLoading">确认转单</el-button>
      </div>
    </el-dialog>

    <!-- 物流面单图片预览弹窗 -->
    <el-dialog
      title="物流面单"
      :visible.sync="logisticsImageDialogVisible"
      width="800px"
      :close-on-click-modal="false"
      center
    >
      <div class="image-preview-container">
        <el-image 
          v-for="(url, idx) in currentLogisticsImageUrls"
          :key="url"
          :src="url"
          style="width: 100%; max-height: 500px; margin-bottom: 10px;"
          fit="contain"
          :preview-src-list="currentLogisticsImageUrls"
          :initial-index="idx"
          lazy
        >
          <div slot="placeholder" class="image-slot">
            <i class="el-icon-loading"></i>
            <p>图片加载中...</p>
          </div>
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
            <p>图片加载失败</p>
          </div>
        </el-image>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="logisticsImageDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 设备图片预览弹窗 -->
    <el-dialog
      title="设备图片"
      :visible.sync="deviceImageDialogVisible"
      width="800px"
      :close-on-click-modal="false"
      center
    >
      <div class="image-preview-container">
        <el-image 
          v-for="(url, idx) in currentDeviceImageUrls"
          :key="url"
          :src="url"
          style="width: 100%; max-height: 500px; margin-bottom: 10px;"
          fit="contain"
          :preview-src-list="currentDeviceImageUrls"
          :initial-index="idx"
          lazy
        >
          <div slot="placeholder" class="image-slot">
            <i class="el-icon-loading"></i>
            <p>图片加载中...</p>
          </div>
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
            <p>图片加载失败</p>
          </div>
        </el-image>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deviceImageDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {deleteOrder, getOrderList, changeOrderStatus, transferOrder, getFactoryListMore } from '@/api/contract';
import { checkToken, handleTokenExpired, checkTokenFromError } from '@/utils/auth';

export default {
  name: 'OrderManagementView',
  data() {
    return {
      // 搜索相关
      searchKeyword: '',
      statusFilter: '', // 状态筛选
      
      // 表格数据
      orderList: [],
      loading: false,
      
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,

      //转单相关
      editTransferOrderDialogVisible:false,

      // 修改弹窗相关
      editDialogVisible: false,
      editForm: {
        id: '',
        status: '',
        track_number: '',
        remark: ''
      },
      editRules: {
      },
      editLoading: false,

      // 转单弹窗相关
      transferOrderDialogVisible: false,
      transferForm: {
        id: '',
        factory_id: '',
        transfer_remark: ''
      },
      transferRules: {
        factory_id: [{ required: true, message: '请选择目标工厂', trigger: 'change' }],
        transfer_remark: [{ required: true, message: '请输入转单原因或备注信息', trigger: 'blur' }]
      },
      transferLoading: false,

      // 工厂列表
      factoryList: [],

      // 图片预览弹窗相关
      logisticsImageDialogVisible: false,
      currentLogisticsImageUrls: [], // 物流面单图片
      deviceImageDialogVisible: false,
      currentDeviceImageUrls: [] // 设备图片
    };
  },
  methods: {
    // 查看物流面单图片（支持多张图片，逗号分隔）
    handleViewLogisticsImage(imageUrl) {
      if (imageUrl) {
        this.currentLogisticsImageUrls = imageUrl.split(',').filter(Boolean);
      } else {
        this.currentLogisticsImageUrls = [];
      }
      this.logisticsImageDialogVisible = true;
    },
    
    // 查看设备图片（支持多张图片，逗号分隔）
    handleViewDeviceImage(imageUrl) {
      if (imageUrl) {
        this.currentDeviceImageUrls = imageUrl.split(',').filter(Boolean);
      } else {
        this.currentDeviceImageUrls = [];
      }
      this.deviceImageDialogVisible = true;
    },

    async handleDeleteOrder(order) {
      try {
        await this.$confirm(`确定要删除该订单吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const response = await deleteOrder(order.id);
        
        if (response.data && response.data.code) {
          this.$message.success('删除订单成功');
          // 重新加载订单列表
          this.fetchOrderList(  );
        } else {
          this.$message.error(response.data.msg || '删除订单失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除');
        } else {
          console.error('删除订单失败:', error);
          this.$message.error('删除订单失败');
        }
      }
    },
    // 获取订单列表
    async fetchOrderList() {
      this.loading = true;
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        const params = {
          keyword: this.searchKeyword,
          status: this.statusFilter, // 添加状态筛选参数
          page: this.currentPage,
          pageSize: this.pageSize
        };
        
        const response = await getOrderList(params);
        
        if (response.data && response.data.code) {
          // API成功返回数据
          this.orderList = response.data.data.data || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$message.error(response.data.msg || '获取订单列表失败');
        }
      } catch (error) {
        console.error('获取订单列表失败:', error);
        if (checkTokenFromError(error)) {
          // Token无效或过期
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          // 其他错误
          this.$message.error('获取订单列表失败');
        }
      } finally {
        this.loading = false;
      }
    },

    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '-';
      const date = new Date(timestamp * 1000);
      return date.toLocaleString('zh-CN');
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchOrderList();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.statusFilter = ''; // 重置状态筛选
      this.currentPage = 1;
      this.fetchOrderList();
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchOrderList();
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchOrderList();
    },

    // 打开修改弹窗
    handleEdit(row) {
      this.editForm = { ...row }; // 复制当前行数据到编辑表单
      this.editDialogVisible = true;
    },

    handleTransferOrder(row) {
      this.transferForm = {
        id: row.id,
        device_name: row.devices ? row.devices.device_name : '未知',
        current_factory: row.factory ? row.factory.factory_name : '未知',
        factory_id: '', // 默认清空
        transfer_remark: ''
      };
      this.transferOrderDialogVisible = true;
    },

    // 提交修改
    async submitEdit() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          this.editLoading = true;
          try {
            // 检查token是否存在
            if (!checkToken()) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
              return;
            }

            const params = {
              id: this.editForm.id,
              status: this.editForm.status,
              track_number: this.editForm.track_number,
              remark: this.editForm.remark
            };

            const response = await changeOrderStatus(params); // 假设 $api 是全局或通过 props 传递的 API 对象

            if (response.data && response.data.code) {
              this.$message.success('订单修改成功');
              this.editDialogVisible = false;
              this.fetchOrderList(); // 刷新列表
            } else {
              this.$message.error(response.data.msg || '订单修改失败');
            }
          } catch (error) {
            console.error('提交订单修改失败:', error);
            if (checkTokenFromError(error)) {
              // Token无效或过期
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
            } else {
              // 其他错误
              this.$message.error('提交订单修改失败');
            }
          } finally {
            this.editLoading = false;
          }
        }
      });
    },

    // 获取状态类型
    getStatusType(status) {
      switch (status) {
        case 1:
          return 'warning';
        case 2:
          return 'info'; 
        case 3:
          return 'primary'; 
        case 4:
          return 'success';
        default:
          return '';
      }
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 1:
          return '待处理';
        case 2:
          return '生产中';
        case 3:
          return '已发货';
        case 4:
          return '已签收'
        default:
          return '未知';
      }
    },

    // 提交转单
    async submitTransferOrder() {
      this.$refs.transferForm.validate(async (valid) => {
        if (valid) {
          this.transferLoading = true;
          try {
            // 检查token是否存在
            if (!checkToken()) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
              return;
            }

            const params = {
              id: this.transferForm.id,
              factory_id: this.transferForm.factory_id,
              transfer_remark: this.transferForm.transfer_remark
            };

            const response = await transferOrder(params); // 调用转单API

            if (response.data && response.data.code) {
              this.$message.success('转单成功');
              this.transferOrderDialogVisible = false;
              this.fetchOrderList(); // 刷新列表
            } else {
              this.$message.error(response.data.msg || '转单失败');
            }
          } catch (error) {
            console.error('提交转单失败:', error);
            if (checkTokenFromError(error)) {
              // Token无效或过期
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
            } else {
              // 其他错误
              this.$message.error('提交转单失败');
            }
          } finally {
            this.transferLoading = false;
          }
        }
      });
    },

    // 获取工厂列表
    async fetchFactoryList() {
      try {
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }
        const response = await getFactoryListMore(); // 假设 $api 是全局或通过 props 传递的 API 对象
        if (response.data && response.data.code) {
          this.factoryList = response.data.msg || [];
        } else {
          this.$message.error(response.data.msg || '获取工厂列表失败');
        }
      } catch (error) {
        console.error('获取工厂列表失败:', error);
        if (checkTokenFromError(error)) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          this.$message.error('获取工厂列表失败');
        }
      }
    }
  },
  
  created() {
    this.fetchOrderList();
    this.fetchFactoryList(); // 在组件创建时获取工厂列表
  }
};
</script>

<style scoped>
.order-management-view {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
}

.pagination-container {
  justify-content: center;
  margin-top: 20px;
  text-align: right !important;
}

.dialog-footer {
  text-align: right;
}

/* 表格样式 */
.el-table {
  border: 1px solid #EBEEF5;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
}

.el-table td, .el-table th {
  border-bottom: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}

.el-table th:last-child,
.el-table td:last-child {
  border-right: none;
}

/* 状态标签样式 */
.el-tag {
  font-weight: 500;
}

/* 配件信息显示样式 */
.accessories-display {
  padding: 8px 0;
}

.accessory-item {
  display: inline-block;
  margin-right: 8px;
}

.accessory-name-tag {
  margin-bottom: 4px;
}

/* 转单弹窗样式 */
.order-info-display {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.order-info-display p {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
}

.order-info-display strong {
  color: #303133;
  font-weight: 600;
}

/* 工厂选择器样式 */
.el-select .el-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 固定列样式 */
.el-table .el-table__fixed-right {
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
}

.el-table .el-table__fixed-right::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 1px;
  height: 100%;
  background-color: #EBEEF5;
}

/* 确保固定列在滚动时正确显示 */
.el-table__body-wrapper {
  overflow-x: auto;
}

/* 图片预览弹窗样式 */
.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 300px;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
  border-radius: 4px;
}

.image-slot p {
  margin: 10px 0 0 0;
  font-size: 14px;
}

.image-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 20px;
}
</style> 